// src/models/sku.model.js
import { DataTypes } from "sequelize";

export default function initSku(sequelize) {
  const Sku = sequelize.define(
    "Sku",
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      product_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "product", // 关联到 product 表
          key: "id",
        },
        comment: "关联的商品ID",
      },
      sku_name: {
        type: DataTypes.STRING(100),
        allowNull: false,
        comment: "SKU名称",
      },
      sku_code: {
        type: DataTypes.STRING(50),
        allowNull: false,
        unique: true,
        comment: "SKU编码",
      },
      price: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false,
        defaultValue: 0.0,
        comment: "价格",
      },
      original_price: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: true,
        comment: "原价",
      },
      stock: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: "库存数量",
      },
      sold: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: "已售数量",
      },
      specs: {
        type: DataTypes.JSON,
        allowNull: false,
        comment: "规格组合，如 {颜色: '红', 尺寸: 'XL'}",
      },
      image: {
        type: DataTypes.STRING(255),
        allowNull: true,
        comment: "SKU特定图片",
      },
      status: {
        type: DataTypes.TINYINT,
        allowNull: false,
        defaultValue: 1,
        comment: "状态：1-上架，0-下架",
      },
    },
    {
      tableName: "sku",
      paranoid: true, // 启用软删除
      indexes: [
        {
          unique: true,
          fields: ["sku_code"],
        },
        {
          fields: ["product_id"],
        },
      ],
    }
  );

  // 关联关系配置
  Sku.associate = function (models) {
    Sku.belongsTo(models.Product, {
      foreignKey: "product_id",
      as: "products",
    });
    // 添加与SkuSpec的一对多关联（关键修复）
    Sku.hasMany(models.SkuSpec, {
      foreignKey: "sku_id",
      as: "skuSpecs", // 必须与查询时的别名一致
    });
    // 添加与SpecValue的多对多关联
    Sku.belongsToMany(models.SpecValue, {
      through: "sku_spec_value", // 中间表名
      foreignKey: "sku_id", // Sku在中间表的外键
      as: "specValue", // 关联别名（必须与查询时一致）
    });
  };

  return Sku;
}
